// 压力测试报告确认
import React from 'react';
import { message, Space } from 'antd';
import { connect } from 'dva';
import { ContentPackage, AdvancedSearch, DATA_ENTRY, PrimaryC, TableC, ModalC, PrimaryGhostC } from '../../comps';
import { exportFile, getUserInfo } from '../../utils/commonFunc';
import LayerContent from './LayerContent';
import styles from './index.less';
import { findTitleByValue } from '../../utils/utils';
import SingleTenantReportModal from './SingleTenantReportModal';

class StressTestReportConform extends React.Component {
  constructor() {
    super();
    this.state = {
      singleTenantVisible: false, // 单租户申请modal
      startDate: '',
      endDate: '',
      visible: false,
      confirmVisiable: false, // 批量确认弹窗
      selectedRowKeys: [], // 选中的checkbox
      selectedRows: [], // 选中项的详情
      searchObj: {}, // 查询的条件
      managerName: [],
      currentPage: 1,
      numInPage: 10,
      total: 0,
      columns: [
        {
          key: 'name',
          title: '报告名称',
        },
        {
          key: 'productNum',
          title: '产品数量',
        },
        {
          key: 'managerName',
          title: '租户',
        },
        {
          key: 'templateName',
          title: '模板名称',
        },
        {
          key: 'sceneName',
          title: '情景名称',
        },
        {
          key: 'reportDate',
          title: '报告日期',
        },
        {
          key: 'status',
          title: '状态',
        },
        {
          key: 'createDate',
          title: '生成时间',
        },
        {
          key: 'needPenetrate',
          title: '是否穿透',
        },
      ],
      dataSource: [],
      statusSource: [
        { title: '生成中', value: 'APPLICATION' },
        { title: '已生成', value: 'WAITING' },
        { title: '已确认', value: 'SUCCESS' },
        { title: '作废', value: 'ZUOFEI' },
        { title: '失败', value: 'FAILURE' },
      ],
      count: 0,
      isReset: false, // 是否点击重置
      managerId: '',
      lackDate: false, // 日期是否选择季度
      tenant: '', // 租户id集合字符串
    };
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'pressureReportM/getScenes',
      payload: {},
    });
    this.props.dispatch({
      type: 'pressureReportM/getTemplate',
      payload: {},
    });
    this.getTableData();
  }

  // 查询表格
  onQuery = (e) => {
    if (this.state.lackDate) {
      message.warning('请选择季度');
      return;
    }
    this.setState(
      {
        isReset: false,
        currentPage: 1,
        numInPage: 10,
        searchObj: e,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 重置
  onClear = () => {
    this.setState({
      isReset: true,
      searchObj: {},
      managerName: [],
      tenant: '',
      startDate: '',
      endDate: '',
      lackDate: false,
    });
  };

  // 申请弹窗展示
  apply = () => {
    this.setState({
      visiable: true,
    });
  };

  // 报告批量确认弹窗展示
  confirm = () => {
    this.setState({
      confirmVisiable: true,
    });
  };

  // 切换分页
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 获取表格数据
  getTableData = () => {
    const { currentPage, tenant, numInPage, searchObj, startDate, endDate, managerName } = this.state;
    this.setState(
      {
        dataSource: undefined,
        selectedRowKeys: [],
        selectedRows: [],
      },
      () => {
        this.props.dispatch({
          type: 'stressTestReportConfirmM/getDataList',
          payload: {
            startDate,
            endDate,
            statusList: searchObj.status || '',
            managerNameList: managerName,
            tenant,
            currentPage,
            numInPage,
          },
          callback: (data) => {
            if (data) {
              this.setState({
                dataSource: data.dataSource,
                total: data.pageInfo.total,
              });
            }
          },
        });
      },
    );
  };

  // 改变勾选
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };

  // 报告申请弹窗确认
  onOk = () => {
    const { dispatch } = this.props;
    this.applyContent.getFormContent((values) => {
      if (values) {
        dispatch({
          type: 'stressTestReportConfirmM/confimApply',
          payload: {
            ...values,
          },
          callback: (res) => {
            if (res) {
              this.setState(
                {
                  visiable: false,
                },
                () => {
                  this.applyContent.clearSelectArr();
                  this.getTableData();
                  // this.applyContent.scrollToTop();
                },
              );
            }
          },
        });
      }
    });
  };

  // 弹窗取消
  onCancel = () => {
    this.setState({
      visiable: false,
    });
    this.applyContent.clearSelectArr();
  };

  // 单个导出
  exportFn = (r) => {
    if (['APPLICATION', 'FAILURE', 'ZUOFEI'].includes(r.status)) return message.info('报告正在导出，请勿重新点击！');
    exportFile('gateway/file/maat-admin/file/download', { uniquekey: r.exportId });
    // if (r.exportId === null) {
    //   exportFile('gateway/maat-risk/stress-test-report/download', { reportId: r.id });
    // } else {
    //   exportFile('gateway/file/maat-admin/file/download', { uniquekey: r.exportId });
    // }
  };

  // 单个报告确认
  confirmFn = (record) => {
    if (['SUCCESS', 'APPLICATION', 'FAILURE', 'ZUOFEI'].includes(record.status)) {
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'stressTestReportConfirmM/confirmList',
      payload: {
        reportIdList: record?.id,
      },
      callback: (res) => {
        if (res) {
          this.getTableData();
        }
      },
    });
  };

  // 删除
  deleteFn = (record) => {
    if (['APPLICATION'].includes(record.status)) return;
    const { dispatch } = this.props;
    dispatch({
      type: 'stressTestReportConfirmM/deleteSingle',
      payload: {
        reportId: record?.id,
        reportType: record?.reportType,
      },
      callback: (res) => {
        if (res) {
          this.getTableData();
        }
      },
    });
  };

  // 资产情况导出
  assetExprot = (record) => {
    if (['APPLICATION', 'FAILURE', 'ZUOFEI'].includes(record.status)) return;
    // 本地测试
    // exportFile('maat/api/python/evar/api/obtain_metadata/get_fund_scale_detailed', {reportId: record?.id})
    // 线上
    exportFile('gateway/file/maat-admin/file/download', { uniquekey: record.exportOfAssetSituationId });
  };

  // 修改columns的状态
  changeColumns = (columns) => {
    const { templateList = [], sceneList = [] } = this.props.pressureReportM;
    const data = columns;
    if (data && data.length) {
      if (data[data.length - 1].title !== '操作') {
        data.push({
          key: 'operate',
          type: 'operate',
          title: '操作',
          width: 260,
          operates: [
            {
              title: '导出',
              onClick: (record, index) => {
                this.exportFn(record);
              },
              rules: {
                disabled: {
                  relation: 'or',
                  items: [
                    {
                      key: 'status',
                      value: ['APPLICATION', 'FAILURE', 'ZUOFEI'],
                      relation: ['=', '=', '='],
                    },
                    {
                      key: 'exportId',
                      value: [null],
                      relation: ['='],
                    },
                  ],
                },
              },
            },
            {
              title: '资产情况导出',
              onClick: (record, index) => {
                this.assetExprot(record);
              },
              rules: {
                disabled: {
                  relation: 'or',
                  items: [
                    {
                      key: 'status',
                      value: ['APPLICATION', 'FAILURE', 'ZUOFEI'],
                      relation: ['=', '=', '='],
                    },
                    // 如果exportOfAssetSituationId有值的话，就是文件上传的，需要把资产情况导出按钮置灰，其他的按钮判断还是原来的逻辑
                    {
                      key: 'exportOfAssetSituationId',
                      value: [null],
                      relation: ['='],
                    },
                  ],
                },
              },
            },
            {
              title: '报告确认',
              onClick: (record, index) => {
                this.confirmFn(record);
              },
              rules: {
                disabled: {
                  relation: 'or',
                  items: [
                    {
                      key: 'status',
                      value: ['SUCCESS', 'APPLICATION', 'FAILURE', 'ZUOFEI'],
                      relation: ['=', '=', '=', '='],
                    },
                    // reportType 0 来自maat 1来自evar  0置灰
                    {
                      key: 'reportType',
                      value: ['0'],
                      relation: ['='],
                    },
                  ],
                },
              },
            },
            {
              title: '删除',
              onClick: (record, index) => {
                this.deleteFn(record);
              },
              rules: {
                disabled: {
                  relation: 'or',
                  items: [
                    {
                      key: 'status',
                      value: ['APPLICATION'],
                      relation: ['='],
                    },
                  ],
                },
              },
            },
          ],
        });
      }
      data.map((item) => {
        if (item.key == 'status') {
          item.width = 80;
          item.render = (text) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              let value;
              this.state.statusSource.map((item) => {
                if (item.value.includes(text)) {
                  value = item.title;
                }
              });
              return value;
            }
          };
        }
        if (item.key == 'productNum') {
          item.align = 'right';
          item.width = 100;
        }
        if (item.key == 'createDate') {
          item.align = 'right';
          item.width = 160;
        }
        if (item.key == 'reportDate') {
          item.width = 100;
          item.type = 'date';
        }
        if (item.key == 'sceneName' || item.key == 'templateName') {
          // 情景名称 模板名称 maat需要手动翻译
          item.width = 80;
          item.render = (text, record) => {
            const showName = findTitleByValue(text, item.key == 'sceneName' ? sceneList : templateList);
            return showName;
            // if (text === null || text === undefined) {
            //   return '--';
            // } else {
            //   if (record.reportType != '0') return text || '--';
            //   return findTitleByValue(text, item.key == 'sceneName' ? sceneList : templateList) || '--';
            // }
          };
        }

        if (item.key == 'needPenetrate') {
          item.width = 80;
          item.render = (text) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              return text == 1 ? '是' : '否';
            }
          };
        }
        if (item.key == 'managerName' || item.key == 'name') {
          item.width = 260;
        }
      });
    }
    return data;
  };

  // 批量确认的确定
  confirmOk = () => {
    const { dispatch } = this.props;
    const { selectedRowKeys } = this.state;
    dispatch({
      type: 'stressTestReportConfirmM/confirmList',
      payload: {
        reportIdList: selectedRowKeys.toString(),
      },
      callback: (res) => {
        if (res) {
          this.setState(
            {
              confirmVisiable: false,
            },
            () => {
              this.getTableData();
            },
          );
        }
      },
    });
  };

  // 批量确认的取消
  confirmCancel = () => {
    this.setState({
      confirmVisiable: false,
    });
  };

  // 单住户显示隐藏
  singleApply = () => {
    this.setState({
      singleTenantVisible: true,
    });
  };

  /**
   * 单住户操作按钮
   * @param buttonType { boolean } 确认/取消
   * @param payload { object } 参数
   */
  operateSingleTenant = (buttonType, payload) => {
    // 确认
    if (buttonType) {
      this.props.dispatch({
        type: 'stressTestReportConfirmM/confimApply',
        payload: {
          managerInfosForReport: [
            {
              ...payload,
            },
          ],
        },
        callback: (res) => {
          if (res) {
            this.setState(
              {
                singleTenantVisible: false,
              },
              () => {
                this.getTableData();
              },
            );
          }
        },
      });
      return;
    }
    // 取消
    if (!buttonType) {
      this.setState({
        singleTenantVisible: false,
      });
    }
  };

  render() {
    const { visiable, columns, dataSource, currentPage, total, numInPage, selectedRowKeys, confirmVisiable, statusSource, singleTenantVisible } = this.state;
    const { loading, confirmLoading, applyLoading } = this.props;
    const dataSourceQuery = [
      {
        yearKey: 'year',
        quarterKey: 'quarter',
        type: DATA_ENTRY.SIMPLEQUARTERC,
        title: '报告时间',
        highCurrentDate: true,
        onQuarterChange: (data) => {
          this.setState({
            startDate: data.beginDate,
            endDate: data.endDate,
            lackDate: !!data.lackDate,
          });
        },
      },
      {
        dataIndex: 'tenant',
        type: DATA_ENTRY.TENANT,
        title: '租户',
        multiple: true,
        onChange: (e) => {
          if (e) {
            const arr = [];
            e &&
              e.info.map((item) => {
                arr.push(item.title);
              });
            this.setState({
              managerName: arr.toString(),
              tenant: e.key?.toString(),
            });
          } else {
            this.setState({
              managerName: [],
              tenant: '',
            });
          }
        },
      },
      {
        dataIndex: 'status',
        type: DATA_ENTRY.SELECT,
        allowClear: true,
        title: '状态',
        dataSource: statusSource,
        isMultiple: true,
      },
    ];
    const newColumns = this.changeColumns(columns);
    // 多选框
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => ({
        disabled: !['WAITING'].includes(record.status), // 配置无法勾选的列 只有 已生成的可以亮
      }),
    };

    return (
      <ContentPackage
        title='压力测试报告确认'
        contentHtml={
          <div>
            <AdvancedSearch dataSource={dataSourceQuery} onQuery={this.onQuery} onClear={this.onClear} />
            <div className={styles.btn}>
              <Space>
                <PrimaryC title='批量报告申请' onClick={this.apply} />
                <PrimaryC title='单租户报告申请' onClick={this.singleApply} />
                <PrimaryC title='报告确认' disabled={!selectedRowKeys?.length} onClick={this.confirm} />
              </Space>
            </div>
            <div style={{ marginTop: '16px' }}>
              <TableC
                columns={newColumns}
                dataSource={dataSource}
                current={currentPage}
                total={total}
                pageSize={numInPage}
                rowKey='id'
                selfScrollY={true}
                onChange={this.handleTableChange}
                rowSelection={rowSelection}
                loading={loading}
              />
            </div>
            <ModalC
              visible={visiable}
              onOk={this.onOk}
              onCancel={this.onCancel}
              title={'批量报告申请'}
              width={420}
              confirmLoading={applyLoading}
              maskClosable={false}
              destroyOnClose={true}
            >
              <LayerContent onRef={(ref) => (this.applyContent = ref)} />
            </ModalC>
            <ModalC visible={confirmVisiable} title={''} width={420} onCancel={this.confirmCancel} destroyOnClose={true} maskClosable={false} footer={null}>
              <div className={styles.confirmContent}>
                <span className={styles.confirmText}>确认为以下报告进行批量确认？</span>
                <PrimaryGhostC title='取消' onClick={this.confirmCancel} />
                <PrimaryC title='确定' onClick={this.confirmOk} loading={confirmLoading} style={{ marginLeft: '16px' }} />
              </div>
            </ModalC>
            {singleTenantVisible && <SingleTenantReportModal visible={singleTenantVisible} operate={this.operateSingleTenant} />}
          </div>
        }
      />
    );
  }
}
export default connect(({ stressTestReportConfirmM, loading, pressureReportM }) => ({
  stressTestReportConfirmM,
  loading: loading.effects['stressTestReportConfirmM/getDataList'],
  confirmLoading: loading.effects['stressTestReportConfirmM/confirmList'],
  applyLoading: loading.effects['stressTestReportConfirmM/confimApply'],
  pressureReportM,
}))(StressTestReportConform);
